package com.wlt.service;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlt.mapper.AdminMapper;
import com.wlt.pojo.Admin;
import com.wlt.pojo.Permission;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@DubboService (timeout = 10000)
@Transactional
public class AdminServiceImpl implements AdminService
{
    @Autowired
    private AdminMapper adminMapper;
    
    /**
     * 增
     */
    @Override
    public void add (Admin admin)
    {
        adminMapper.insert(admin);
    }
    
    /**
     * 改
     */
    @Override
    public void update (Admin admin)
    {
        // 如果前端传来的是空密码那么密码还是原来的密码
        if (!StringUtils.hasText(admin.getPassword()))
        {
            // 查询原来的密码
            String password = adminMapper.selectById(admin.getAid()).getPassword();
            // 把原来的密码设置为现在的密码
            admin.setPassword(password);
        }
        adminMapper.updateById(admin);
    }
    
    /**
     * 删
     */
    @Override
    public void delete (Long id)
    {
        // 删除用户的所有角色
        adminMapper.deleteAdminAllRole(id);
        // 删除用户
        adminMapper.deleteById(id);
    }
    
    /**
     * 按id查
     */
    @Override
    public Admin findById (Long id)
    {
        return adminMapper.findById(id);
    }
    
    /**
     * 分页查
     * @param page 页
     * @param size 每页展示
     */
    @Override
    public Page<Admin> serachPage (int page, int size)
    {
        return adminMapper.selectPage(new Page(page, size), null);
    }
    
    /**
     * 修改管理员角色
     */
    @Override
    public void updateRoleToAdmin (Long aid, Long[] rids)
    {
        // 先删老角色
        adminMapper.deleteAdminAllRole(aid);
        
        // 再加新角色
        for (Long rid: rids)
        {
            adminMapper.addRoleToAdmin (aid, rid);
        }
    }
    
    @Override
    public Admin findByAdminName (String username)
    {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        
        Admin admin = adminMapper.selectOne(queryWrapper);
        
        return admin;
    }
    
    @Override
    public List<Permission> findAllPermission (String username)
    {
        return adminMapper.findAllPermission(username);
    }
}
